#include "vehicle_view_model.h"
#include "kernel/agv/agv_entity.h"

namespace presentation {
namespace viewmodels {

namespace {
AgvListModel::DisplayState computeDisplayState(const kernel::dtos::AgvInfoDTO& agv) {
    if (!agv.online) return AgvListModel::DisplayState::Offline;
    // 将锁定视为急停优先级
    if (agv.locked) return AgvListModel::DisplayState::EstopOrLocked;
    if (agv.blocked) return AgvListModel::DisplayState::Blocked;
    if (agv.charging) return AgvListModel::DisplayState::Charging;
    if (agv.taskStatus == static_cast<int>(kernel::agv::NavStatus::Running) ||
        agv.isControlledByDispatcher) {
        return AgvListModel::DisplayState::Executing;
    }
    return AgvListModel::DisplayState::Idle;
}

QStringList buildStatusTags(const kernel::dtos::AgvInfoDTO& agv) {
    QStringList tags;
    if (!agv.online) tags << QStringLiteral("离线");
    if (agv.locked) tags << QStringLiteral("急停");
    if (agv.blocked) tags << QStringLiteral("阻挡");
    if (agv.charging) tags << QStringLiteral("充电");
    if (agv.isControlledByDispatcher ||
        agv.taskStatus == static_cast<int>(kernel::agv::NavStatus::Running)) {
        tags << QStringLiteral("执行");
    }
    if (agv.mode == static_cast<int>(kernel::agv::AgvMode::Manual)) {
        tags << QStringLiteral("手动");
    }
    return tags;
}
}  // namespace

// AgvListModel实现
AgvListModel::AgvListModel(QObject* parent)
    : QAbstractListModel(parent)
{
}

int AgvListModel::rowCount(const QModelIndex& parent) const
{
    Q_UNUSED(parent);
    return static_cast<int>(m_agvList.size());
}

QVariant AgvListModel::data(const QModelIndex& index, int role) const
{
    if (index.row() < 0 || index.row() >= static_cast<int>(m_agvList.size())) {
        return QVariant();
    }

    const auto& agv = m_agvList[index.row()];

    switch (role) {
    case AgvNumberRole:
        return agv.agvNumber;
    case NameRole:
        return agv.name;
    case IpAddressRole:
        return agv.ip;
    case TypeRole:
        return agv.type;
    case LocationRole:
    case CurrentStationRole:
        return agv.currentStation;
    case LastStationRole:
        return agv.lastStation;
    case TargetStationRole:
        return agv.targetStation;
    case CurrentMapRole:
        return agv.currentMap;
    case CurrentJobRole:
        return agv.targetStation.isEmpty() ? QString("Idle") : QString("Moving to %1").arg(agv.targetStation);
    case XRole:
        return agv.x;
    case YRole:
        return agv.y;
    case AngleRole:
        return agv.angle;
    case ConfidenceRole:
        return agv.confidence;
    case BatteryLevelRole:
        return agv.power;
    case IsOnlineRole:
        return agv.online;
    case IsChargingRole:
        return agv.charging;
    case IsLockedRole:
        return agv.locked;
    case IsBlockedRole:
        return agv.blocked;
    case ModeRole:
        return agv.mode;
    case TaskStatusRole:
        return agv.taskStatus;
    case TaskTypeRole:
        return agv.taskType;
    case IsControlledRole:
        return agv.isControlledByDispatcher;
    case ErrorMessageRole:
        return agv.errorMessage;
    case UploadTimeRole:
        return agv.uploadTime;
    case FinishedPathRole:
        return QVariant::fromValue(agv.finishedPath);
    case UnfinishedPathRole:
        return QVariant::fromValue(agv.unfinishedPath);
    case PathLengthRole:
        return agv.unfinishedPath.size();
    case TaskChainIdRole:
        // 任务链ID可以通过目标站点推断（如果有的话）
        return agv.targetStation.isEmpty() ? QVariant() : QString("task_%1").arg(agv.agvNumber);
    case IsBusyRole:
        return agv.taskStatus == 2 || !agv.targetStation.isEmpty(); // 2=RUNNING
    case DisplayStateRole:
        return static_cast<int>(computeDisplayState(agv));
    case StatusTagsRole:
        return buildStatusTags(agv);
    default:
        return QVariant();
    }
}

QHash<int, QByteArray> AgvListModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[AgvNumberRole] = "agvNumber";
    roles[NameRole] = "name";
    roles[IpAddressRole] = "ipAddress";
    roles[TypeRole] = "type";
    roles[LocationRole] = "location";
    roles[CurrentStationRole] = "currentStation";
    roles[LastStationRole] = "lastStation";
    roles[TargetStationRole] = "targetStation";
    roles[CurrentMapRole] = "currentMap";
    roles[CurrentJobRole] = "currentJob";
    roles[XRole] = "x";
    roles[YRole] = "y";
    roles[AngleRole] = "angle";
    roles[ConfidenceRole] = "confidence";
    roles[BatteryLevelRole] = "batteryLevel";
    roles[IsOnlineRole] = "isOnline";
    roles[IsChargingRole] = "isCharging";
    roles[IsLockedRole] = "isLocked";
    roles[IsBlockedRole] = "isBlocked";
    roles[ModeRole] = "mode";
    roles[TaskStatusRole] = "taskStatus";
    roles[TaskTypeRole] = "taskType";
    roles[IsControlledRole] = "isControlled";
    roles[ErrorMessageRole] = "errorMessage";
    roles[UploadTimeRole] = "uploadTime";
    roles[FinishedPathRole] = "finishedPath";
    roles[UnfinishedPathRole] = "unfinishedPath";
    roles[PathLengthRole] = "pathLength";
    roles[TaskChainIdRole] = "taskChainId";
    roles[IsBusyRole] = "isBusy";
    roles[DisplayStateRole] = "displayState";
    roles[StatusTagsRole] = "statusTags";
    return roles;
}

QVariantMap AgvListModel::getAgvData(int row) const
{
    QVariantMap result;

    if (row < 0 || row >= static_cast<int>(m_agvList.size())) {
        return result;
    }

    const auto& agv = m_agvList[row];

    // 基本信息
    result["id"] = agv.agvNumber;  // VehicleDetailsView uses "id"
    result["agvNumber"] = agv.agvNumber;
    result["name"] = agv.name;
    result["model"] = agv.type;  // VehicleDetailsView uses "model"
    result["ip"] = agv.ip;
    result["type"] = agv.type;

    // 位置信息
    result["x"] = agv.x;
    result["y"] = agv.y;
    result["angle"] = agv.angle;
    result["confidence"] = agv.confidence;
    result["currentStation"] = agv.currentStation;
    result["lastStation"] = agv.lastStation;
    result["targetStation"] = agv.targetStation;
    result["currentMap"] = agv.currentMap;

    // 状态信息
    result["status"] = agv.online ? (agv.blocked ? "blocked" : "running") : "offline";
    result["battery"] = agv.power;
    result["isCharging"] = agv.charging;
    result["isLocked"] = agv.locked;
    result["isBlocked"] = agv.blocked;
    result["online"] = agv.online;
    result["mode"] = agv.mode;

    // 任务信息
    result["taskStatus"] = agv.taskStatus;
    result["taskType"] = agv.taskType;
    result["currentTask"] = agv.targetStation.isEmpty() ? QVariant() : agv.targetStation;
    result["isControlled"] = agv.isControlledByDispatcher;

    // 错误信息
    result["errorMessage"] = agv.errorMessage;

    // 路径信息
    result["finishedPath"] = QVariant::fromValue(agv.finishedPath);
    result["unfinishedPath"] = QVariant::fromValue(agv.unfinishedPath);
    result["pathLength"] = agv.unfinishedPath.size();
    result["isBusy"] = agv.taskStatus == 2 || !agv.targetStation.isEmpty();

    // 时间信息
    result["uploadTime"] = agv.uploadTime;
    result["registerTime"] = agv.uploadTime;  // 使用uploadTime作为registerTime

    // VehicleDetailsView 期望但 AgvInfoDTO 中没有的字段，使用默认值
    result["serialNumber"] = QVariant();  // 未设置
    result["speed"] = 0.0;  // 暂无速度数据
    result["voltage"] = 0.0;  // 暂无电压数据
    result["current"] = 0.0;  // 暂无电流数据
    result["estimatedRuntime"] = 0.0;  // 暂无预估运行时间
    result["taskProgress"] = 0;  // 暂无任务进度
    result["completedTasks"] = 0;  // 暂无完成任务数
    result["totalRuntime"] = 0;  // 暂无总运行时间
    result["emergencyStop"] = false;  // 暂无急停状态

    // 传感器状态（暂无数据）
    QVariantMap sensors;
    sensors["lidar"] = true;
    sensors["camera"] = true;
    sensors["ultrasonic"] = true;
    result["sensors"] = sensors;

    return result;
}

QVariantMap AgvListModel::getAgvDataByNumber(int agvNumber) const
{
    return getAgvData(indexOfAgv(agvNumber));
}

int AgvListModel::indexOfAgv(int agvNumber) const
{
    for (int i = 0; i < static_cast<int>(m_agvList.size()); ++i) {
        if (m_agvList[static_cast<size_t>(i)].agvNumber == agvNumber) {
            return i;
        }
    }
    return -1;
}

void AgvListModel::updateData(const std::vector<kernel::dtos::AgvInfoDTO>& agvList)
{
    beginResetModel();
    m_agvList = agvList;
    endResetModel();
}

void AgvListModel::updateAgv(int agvNumber, const kernel::dtos::AgvInfoDTO& agv)
{
    for (size_t i = 0; i < m_agvList.size(); ++i) {
        if (m_agvList[i].agvNumber == agvNumber) {
            m_agvList[i] = agv;
            QModelIndex idx = index(static_cast<int>(i));
            emit dataChanged(idx, idx);
            return;
        }
    }

    // 如果没找到，添加新项
    beginInsertRows(QModelIndex(), rowCount(), rowCount());
    m_agvList.push_back(agv);
    endInsertRows();
}

// VehicleViewModel实现
// Default constructor for QML instantiation
VehicleViewModel::VehicleViewModel(QObject* parent)
    : BaseViewModel(parent)
    , m_vehicleService(nullptr)
    , m_agvListModel(std::make_unique<AgvListModel>(this))
    , m_refreshTimer(std::make_unique<QTimer>(this))
{
    // Demo mode - initialize with empty data

    // Delayed initialization to ensure QML bindings are ready
    delayedInitialize();
}

VehicleViewModel::VehicleViewModel(
    application::vehicle::VehicleService* vehicleService,
    QObject* parent)
    : BaseViewModel(parent)
    , m_vehicleService(vehicleService)
    , m_agvListModel(std::make_unique<AgvListModel>(this))
    , m_refreshTimer(std::make_unique<QTimer>(this))
{
    if (!m_vehicleService) { 
        handleError("VehicleViewModel: VehicleService is null!");
        return;
    }

    // Connect signals when service is available
    connect(m_refreshTimer.get(), &QTimer::timeout, this, &VehicleViewModel::onRefreshTimer);

    // Delayed initialization to ensure QML bindings are ready
    delayedInitialize();
}

void VehicleViewModel::refreshAgvList()
{
    if (!m_vehicleService) {
        return;
    }

    auto agvList = m_vehicleService->getAllAgvs();
    m_agvListModel->updateData(agvList);

    updateStatistics();
}

void VehicleViewModel::startCharging(int agvNumber)
{
    if (!m_vehicleService) {
        handleError("VehicleService not available");
        return;
    }

    // 需要从配置获取充电点，这里暂时使用空字符串
    if (!m_vehicleService->startCharging(agvNumber, "")) {
        handleError(QString("Failed to start charging for AGV %1").arg(agvNumber));
    }
}

void VehicleViewModel::stopCharging(int agvNumber)
{
    if (!m_vehicleService) {
        handleError("VehicleService not available");
        return;
    }

    if (!m_vehicleService->stopCharging(agvNumber)) {
        handleError(QString("Failed to stop charging for AGV %1").arg(agvNumber));
    }
}

void VehicleViewModel::cancelTask(int agvNumber)
{
    if (!m_vehicleService) {
        handleError("VehicleService not available");
        return;
    }

    if (!m_vehicleService->cancelAgvTask(agvNumber)) {
        handleError(QString("Failed to cancel task for AGV %1").arg(agvNumber));
    }
}

void VehicleViewModel::controlJack(int agvNumber, bool raise)
{
    if (!m_vehicleService) {
        handleError("VehicleService not available");
        return;
    }

    if (!m_vehicleService->controlJack(agvNumber, raise)) {
        handleError(QString("Failed to control jack for AGV %1").arg(agvNumber));
    }
}

void VehicleViewModel::pauseTask(int agvNumber)
{
    if (!m_vehicleService) {
        handleError("VehicleService not available");
        return;
    }

    if (!m_vehicleService->pauseAgvTask(agvNumber)) {
        handleError(QString("Failed to pause task for AGV %1").arg(agvNumber));
    }
}

void VehicleViewModel::resumeTask(int agvNumber)
{
    if (!m_vehicleService) {
        handleError("VehicleService not available");
        return;
    }

    if (!m_vehicleService->resumeAgvTask(agvNumber)) {
        handleError(QString("Failed to resume task for AGV %1").arg(agvNumber));
    }
}

void VehicleViewModel::goToStation(int agvNumber, const QString& station)
{
    if (!m_vehicleService) {
        handleError("VehicleService not available");
        return;
    }

    // 使用 "SELF_POSITION" 作为起点，表示从当前位置出发
    auto result = m_vehicleService->moveVehicleToStation(
        agvNumber,
        "SELF_POSITION",
        station.toStdString()
    );

    if (!result.isSuccess()) {
        handleError(QString("Failed to move AGV %1 to station %2: %3")
            .arg(agvNumber)
            .arg(station)
            .arg(result.getErrorMessage()));
        return;
    }

    cacheTargetStation(agvNumber, station);
}

QVariantList VehicleViewModel::getRecentTargetStations(int agvNumber) const
{
    QVariantList list;
    if (agvNumber <= 0) {
        return list;
    }

    const auto stations = m_recentTargetStations.value(agvNumber);
    for (const auto& station : stations) {
        list.append(station);
    }
    return list;
}

void VehicleViewModel::onRefreshTimer()
{
    refreshAgvList();
}

void VehicleViewModel::onVehicleStatusChanged(int agvNumber)
{
    if (!m_vehicleService) {
        return;
    }

    // 更新单个AGV的数据
    auto agvDto = m_vehicleService->getAgv(agvNumber);
    if (agvDto.agvNumber != 0) {
        m_agvListModel->updateAgv(agvNumber, agvDto);
    }

    updateStatistics();
    emit agvDataUpdated(agvNumber);
}

void VehicleViewModel::onVehicleRegistered(int agvNumber)
{
    if (!m_vehicleService) {
        return;
    }

    // 刷新整个列表
    refreshAgvList();
}

void VehicleViewModel::onVehicleUnregistered(int agvNumber)
{
    if (!m_vehicleService) {
        return;
    }

    // 刷新整个列表
    refreshAgvList();
}

void VehicleViewModel::onVehicleIdle()
{
    // 所有车辆空闲时的处理
    updateStatistics();
}

void VehicleViewModel::updateStatistics()
{
    if (!m_vehicleService) {
        return;
    }

    auto agvList = m_vehicleService->getAllAgvs();

    int total = static_cast<int>(agvList.size());
    int online = 0;
    int idle = 0;

    for (const auto& agv : agvList) {
        if (agv.online) {
            online++;
        }
        if (agv.online && !agv.isControlledByDispatcher && !agv.charging) {
            idle++;
        }
    }

    if (m_totalAgvCount != total) {
        m_totalAgvCount = total;
        emit totalAgvCountChanged();
    }

    if (m_onlineAgvCount != online) {
        m_onlineAgvCount = online;
        emit onlineAgvCountChanged();
    }

    if (m_idleAgvCount != idle) {
        m_idleAgvCount = idle;
        emit idleAgvCountChanged();
    }
}

void VehicleViewModel::cacheTargetStation(int agvNumber, const QString& station)
{
    if (agvNumber <= 0) {
        return;
    }

    const QString trimmed = station.trimmed();
    if (trimmed.isEmpty()) {
        return;
    }

    auto list = m_recentTargetStations.value(agvNumber);
    const int existingIndex = list.indexOf(trimmed);
    bool changed = false;

    if (existingIndex == 0 && list.size() <= 5) {
        // Already at the front, no change required
        return;
    }

    if (existingIndex > 0) {
        list.removeAt(existingIndex);
        changed = true;
    } else if (existingIndex == -1) {
        changed = true;
    }

    list.prepend(trimmed);
    while (list.size() > 5) {
        list.removeLast();
    }

    if (!changed && m_recentTargetStations.value(agvNumber) == list) {
        return;
    }

    m_recentTargetStations.insert(agvNumber, list);
    m_targetHistoryRevision++;
    emit targetHistoryRevisionChanged();
}

void VehicleViewModel::createSimulationVehicle(const QVariantMap& data)
{
    if (!m_vehicleService) {
        handleError("VehicleService 不可用");
        return;
    }

    try {
        int agvNumber = data.value("agvNumber").toInt();
        QString name = data.value("name").toString();
        QString initialMap = data.value("initialMap", "XP2F").toString();
        QString initialStation = data.value("initialStation").toString();
        double heading = data.value("heading", 0.0).toDouble();
        int batteryLevel = data.value("batteryLevel", 90).toInt();
        int maxSpeed = data.value("maxSpeed", 800).toInt();

        if (agvNumber <= 0 || name.isEmpty() || initialStation.isEmpty()) {
            handleError("无效的仿真车辆数据");
            return;
        }

        // 检查车辆是否已存在
        if (m_vehicleService->getVehicle(agvNumber)) {
            handleError(QString("车辆 AGV%1 已存在").arg(agvNumber));
            return;
        }

        // TODO: 完整的仿真车辆创建需要:
        // 1. 创建 SimAgvCommand 实例
        // 2. 创建 SimStatusProvider 实例
        // 3. 通过 VehicleService::registerVehicle() 注册车辆
        // 4. 通过 VehicleService::registerVehicleStatusProvider() 注册状态提供者
        // 5. 通过 SimulationEngine::registerVehicle() 在仿真引擎中注册
        // 6. 通过 PhysicsSimulator::registerVehicle() 在物理模拟器中注册
        //
        // 这些需要访问 SimulationService 和 SimulationEngine 实例
        // 当前暂时只记录日志,提示功能未完全实现

        // 记录创建请求
        qDebug() << "创建仿真车辆请求:"
                 << "编号=" << agvNumber
                 << "名称=" << name
                 << "地图=" << initialMap
                 << "站点=" << initialStation
                 << "朝向=" << heading
                 << "电量=" << batteryLevel
                 << "速度=" << maxSpeed;

        // 刷新列表
        refreshAgvList();

    } catch (const std::exception& e) {
        handleError(QString("创建仿真车辆失败: %1").arg(e.what()));
    }
}

void VehicleViewModel::updateSimulationVehicle(const QVariantMap& data)
{
    if (!m_vehicleService) {
        handleError("VehicleService 不可用");
        return;
    }

    try {
        int agvNumber = data.value("agvNumber").toInt();
        QString name = data.value("name").toString();
        QString initialMap = data.value("initialMap", "XP2F").toString();
        QString initialStation = data.value("initialStation").toString();
        double heading = data.value("heading", 0.0).toDouble();
        int batteryLevel = data.value("batteryLevel", 90).toInt();
        int maxSpeed = data.value("maxSpeed", 800).toInt();

        if (agvNumber <= 0) {
            handleError("无效的车辆编号");
            return;
        }

        // 检查车辆是否存在
        if (!m_vehicleService->getVehicle(agvNumber)) {
            handleError(QString("车辆 AGV%1 不存在").arg(agvNumber));
            return;
        }

        // TODO: 更新仿真车辆参数需要:
        // 1. 更新车辆实体的属性 (名称等)
        // 2. 更新物理模拟器中的参数 (位置、朝向、速度等)
        // 3. 可能需要重新初始化状态提供者
        //
        // 当前暂时只记录日志

        // 记录更新请求
        qDebug() << "更新仿真车辆请求:"
                 << "编号=" << agvNumber
                 << "名称=" << name
                 << "地图=" << initialMap
                 << "站点=" << initialStation
                 << "朝向=" << heading
                 << "电量=" << batteryLevel
                 << "速度=" << maxSpeed;

        // 刷新列表
        refreshAgvList();

    } catch (const std::exception& e) {
        handleError(QString("更新仿真车辆失败: %1").arg(e.what()));
    }
}

void VehicleViewModel::deleteSimulationVehicle(int agvNumber)
{
    if (!m_vehicleService) {
        handleError("VehicleService 不可用");
        return;
    }

    try {
        if (agvNumber <= 0) {
            handleError("无效的车辆编号");
            return;
        }

        // 检查车辆是否存在
        if (!m_vehicleService->getVehicle(agvNumber)) {
            handleError(QString("车辆 AGV%1 不存在").arg(agvNumber));
            return;
        }

        // 注销车辆 (这会触发 VehicleService 的 unregisterVehicle)
        m_vehicleService->unregisterVehicle(agvNumber);

        // TODO: 还需要从仿真引擎和物理模拟器中注销
        // 当前 VehicleService::unregisterVehicle() 只处理了车辆实体的移除

        // 记录删除操作
        qDebug() << "删除仿真车辆: AGV" << agvNumber;

        // 刷新列表
        refreshAgvList();

    } catch (const std::exception& e) {
        handleError(QString("删除仿真车辆失败: %1").arg(e.what()));
    }
}

void VehicleViewModel::initialize()
{
    if (isInitialized()) {
        return;
    }

    try {
        if (m_vehicleService) {
            // Connect VehicleService signals to ViewModel slots
            connect(m_vehicleService, &application::vehicle::VehicleService::vehicleStatusChanged,
                    this, &VehicleViewModel::onVehicleStatusChanged);
            connect(m_vehicleService, &application::vehicle::VehicleService::vehicleRegistered,
                    this, &VehicleViewModel::onVehicleRegistered);
            connect(m_vehicleService, &application::vehicle::VehicleService::vehicleUnregistered,
                    this, &VehicleViewModel::onVehicleUnregistered);
            connect(m_vehicleService, &application::vehicle::VehicleService::vehicleIdle,
                    this, &VehicleViewModel::onVehicleIdle);

            // Setup refresh timer
            m_refreshTimer->setInterval(1000);  // 1 second refresh
            m_refreshTimer->start();

            // Initial data load
            refreshAgvList();
        }

        // Call base class initialization
        BaseViewModel::initialize();

    } catch (const std::exception& e) {
        handleError(QString("VehicleViewModel initialization failed: %1").arg(e.what()));
    }
}

void VehicleViewModel::cleanup()
{
    if (!isInitialized()) {
        return;
    }

    try {
        // Stop refresh timer
        if (m_refreshTimer) {
            m_refreshTimer->stop();
        }

        // Disconnect from service
        if (m_vehicleService) {
            disconnect(m_vehicleService, &application::vehicle::VehicleService::vehicleStatusChanged,
                       this, &VehicleViewModel::onVehicleStatusChanged);
            disconnect(m_vehicleService, &application::vehicle::VehicleService::vehicleRegistered,
                       this, &VehicleViewModel::onVehicleRegistered);
            disconnect(m_vehicleService, &application::vehicle::VehicleService::vehicleUnregistered,
                       this, &VehicleViewModel::onVehicleUnregistered);
            disconnect(m_vehicleService, &application::vehicle::VehicleService::vehicleIdle,
                       this, &VehicleViewModel::onVehicleIdle);
        }

        // Clear data
        m_agvListModel->updateData({});
        m_totalAgvCount = 0;
        m_onlineAgvCount = 0;
        m_idleAgvCount = 0;

        // Call base class cleanup
        BaseViewModel::cleanup();

    } catch (const std::exception& e) {
        handleError(QString("VehicleViewModel cleanup failed: %1").arg(e.what()));
    }
}

} // namespace viewmodels
} // namespace presentation
